package _08;

/**
 * 
 * Good Question.
 * I suck at the index problem. Need to practice again.
 *
 */
public class Solution {
    public static void drawLine(byte[] screen, int width, int x1, int x2, int y) {
    	/**
    	 * Good Question.
    	 * >> is of very low priority.
    	 * Should use parentheses instead.
    	 */
	int leftByte = y * width + (x1 >> 3);
	int rightByte = y * width + (x2 >> 3);
//			y * width + x2 >> 3 + 1;
	int leftBit = 0;
	int rightBit = 7;
	if (x1 % 8 != 0) {
	    leftByte++;
	    leftBit = 8 - (x1 % 8);
	}
	if (x2 % 8 != 7) {
	    rightByte--;
	    rightBit = (x2 % 8);
	}
	for (int i = leftByte; i <= rightByte; i++) {
	    screen[i] = (byte)(0xFF);
	}
	if (leftByte > rightByte) {
		int index = y * width + x1 / 8;
		for (int i = 7 - x1 % 8; i >= 7 - x2 % 8; i--) {
			screen[index] |= (1 << i);
		}
		return;
	}
	if (leftBit != 0) {
	    for (int i = 0; i < leftBit; i++) {
		screen[leftByte-1] |= (1 << i);
	    }
	}
	if (rightBit != 7) {
	    for (int i = rightBit; i >= 0; i--) {
		screen[rightByte+1] |= (1 << (7 - i));
	    }
	}
    }

    public static void printScreen(byte[] screen, int width) {
	for (int i = 0; i < screen.length; i++) {
	    if (i % width == 0) {
		System.out.println();
	    }
	    for (int j = 7; j >= 0; j--) {
		if ((screen[i] & (1 << j)) > 0) {
		    System.out.print("X");
		} else {
		    System.out.print("O");
		}
	    }
	}
    }

    public static void main(String[] args) {
	final int UNIT = 8;
	int width = 4;
	int hight = 1;
	int total = hight * width;
	byte[] screen = new byte[total];
	int x1 = 2;
	int x2 = 3
//			27
			;
	int y = (int)(hight * Math.random());
	drawLine(screen, width, x1, x2, y);
	printScreen(screen, width);
    }
}